package com.example.test06thread.cyclicbarrierTest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author EDZ
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new YourThread());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        executor.execute(new MyThread(cyclicBarrier, "test1", 1));
        executor.execute(new MyThread(cyclicBarrier, "test2", 3));
        executor.execute(new MyThread(cyclicBarrier, "test3", 6));
        executor.shutdown();
    }

    public static class MyThread implements Runnable {
        private final CyclicBarrier cyclicBarrier;
        private final String name;
        private final long timeOut;

        public MyThread(CyclicBarrier cyclicBarrier, String name, long timeOut) {
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
            this.timeOut = timeOut;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(timeOut * 1000);
                System.out.println(printDate() + " " + name + " come in!");
                cyclicBarrier.await();
                System.out.println(printDate() + " " + name + " ending!");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public static class YourThread implements Runnable {

        @Override
        public void run() {
            System.out.println(printDate() + " " + "dangdang!");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static String printDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        return sdf.format(new Date());
    }
}